home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 385 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.3 KB

  1. Path: news.mira.net.au!news
  2. From: davidw@werple.net.au (David White)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Strange (to me) notation - little help?
  5. Date: 4 Jan 1996 19:49:53 +1100
  6. Organization: Werple Internet, Melbourne
  7. Message-ID: <4cg4bh$hp1@werple.net.au>
  8. References: <30EB32AC.2836@sierra.net>
  9. NNTP-Posting-Host: werple.mira.net.au
  10.  
  11. "Tyler G. Colwell" <snowbull@sierra.net> writes:
  12.  
  13. >I am reading Jesse Liberty's "Teach Yourself C++ in 21 Days" and have come across some notation that I can't 
  14. >find explained anywhere.  Here is a code fragment of a constructor that he uses in listing 9.4:
  15.  
  16. >***********************************************
  17. > class SimpleCat
  18. > {
  19. >    public:
  20. >       SimpleCat (int age, int weight);
  21. >       ~SimpleCat() {}
  22. >       int GetAge() { return itsAge; }
  23. >       int GetWeight() { return itsWeight; }
  24. >    private:
  25. >       int itsAge;
  26. >       int itsWeight;
  27. > };
  28.  
  29. > SimpleCat::SimpleCat(int age, int weight):
  30. > itsAge(age), itsWeight(weight) {}
  31. >***********************************************
  32.  
  33. >Wow, those last two lines are dumbfounding.  What is the colon at the end of that one line for, and what's up 
  34. >with using members itsAge and itsWeight as functions in the last line, and howcome none of them are inside the 
  35. >braces?
  36.  
  37. >Looking forward to some clarification on this one...
  38.  
  39. The colon introduces the constructor's initializer list, within which you
  40. can initialize the base class constructor and any member objects. For
  41. consistency with the initialization syntax used for user-defined types,
  42. built-in types may use the same syntax, e.g., int x(5) creates an int and
  43. gives it an initial value of 5. In your example, an initializer list is
  44. not required; initialization could have been deferred to the c'tor body.
  45. However, there are many cases in which an initializer list is necessary,
  46. such as the construction of base class or member objects that do not have
  47. default constructors, and reference members. For example: 
  48.  
  49.     struct A
  50.     { A(int i) { n = i; }
  51.       int n;
  52.     };
  53.  
  54.     struct B : public A
  55.     { B() : A(7) {}  //Initializer list required
  56.     };
  57.  
  58. Class A's constructor must be called before execution enters the body of
  59. B's constructor, but because A does not have a default constructor, it is
  60. necessary to provide an initializer list that determines how A's
  61. constructor should be called. 
  62.  
  63. David White
  64. davidw@werple.mira.net.au
  65.  
  66.